import path from 'path'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx' // vue-jsx解析器插件，支持jsx语法
import vueSetupExtend from 'vite-plugin-vue-setup-extend' // 支持script上写上name属性
import viteCompression from 'vite-plugin-compression' // 性能优化
import { createHtmlPlugin } from 'vite-plugin-html' // html模板控制
import { Plugin as importToCDN } from 'vite-plugin-cdn-import' // cdn
import { visualizer } from 'rollup-plugin-visualizer' // 分析报表
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' // 支持svg-icon

// 尽量使用回调函数形式的配置项，更灵活
export default defineConfig(({ mode }) => {
  const isProduction = mode === 'prod'
  const isSit = mode === 'sit'
  const env = loadEnv(mode, path.resolve(process.cwd(), 'env'), 'VITE_APP') // 加载环境变量文件里面定义的变量
  return {
    base: env.VITE_APP_PUBLIC_PATH,
    envDir: 'env', // 指定环境变量文件的文件夹
    plugins: [
      vue(),
      vueJsx(),
      isSit && visualizer({ open: true, emitFile: true, filename: 'report.html' }),
      vueSetupExtend(),
      createHtmlPlugin({
        minify: isProduction,
        pages: [
          {
            template: './index.html',
            injectOptions: {
              data: {
                title: env.VITE_APP_TITLE
              }
            }
          }
        ]
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
        symbolId: '[name]'
      }),
      isProduction && viteCompression(),
      isProduction &&
        importToCDN({
          modules: [
            {
              name: 'vue',
              var: 'Vue',
              path: 'https://unpkg.com/vue@3.4.21'
            },
            {
              name: 'vue-demi',
              var: 'VueDemi',
              path: 'https://unpkg.com/vue-demi@0.14.7'
            },
            {
              name: 'vue-router',
              var: 'VueRouter',
              path: 'https://unpkg.com/vue-router@4.2.4'
            },
            {
              name: 'axios',
              var: 'axios',
              path: 'https://unpkg.com/axios@1.6.8'
            },
            {
              name: 'element-plus',
              var: 'ElementPlus',
              path: 'https://unpkg.com/element-plus@2.6.2',
              css: 'https://unpkg.com/element-plus/dist/index.css'
            }
          ]
        })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    build: {
      assetsDir: 'static',
      modulePreload: {
        polyfill: true
      },
      emptyOutDir: true,
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/name-[hash].[ext]'
        }
      },
      target: 'modules',
      minify: 'terser',
      assetsInlineLimit: '4096', // 小于此阈值的导入或引用资源将内联为 base64 编码
      cssCodeSplit: true, // 启用 CSS 代码拆分
      sourcemap: false, // 构建后是否生成 source map 文件
      brotliSize: true, // 启用 brotli 压缩大小报告
      chunkSizeWarningLimit: 500 // chunk 大小警告的限制
    },
    server: {
      host: '0.0.0.0',
      hmr: true,
      strictPort: false,
      open: true,
      proxy: {
        '/api': {
          target: env.VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
        '/upload': {
          target: 'https://jsonplaceholder.typicode.com',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/upload/, '')
        }
      }
    }
  }
})
